package cz.data.common.security.core;

import cz.data.common.core.DataConstant;
import cz.data.domain.security.rpc.OAuth2ServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Slf4j
public class NacosServiceAuthenticationFilter extends OncePerRequestFilter {

    private final OAuth2ServiceFeign oAuth2ServiceFeign;

    public NacosServiceAuthenticationFilter(OAuth2ServiceFeign oAuth2ServiceFeign) {
        this.oAuth2ServiceFeign = oAuth2ServiceFeign;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader(DataConstant.Token.SERVICE_HEADER);
        if (StringUtils.isNotBlank(authorization)) {
            try {
                oAuth2ServiceFeign.nacosService(authorization);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authorization, null, Collections.emptyList());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            } catch (Exception e) {
                log.warn("Nacos内部鉴权错误: {}", e.getMessage());
            }
        }
        filterChain.doFilter(request, response);
    }
}
